import { useEffect, useState, useRef, useLayoutEffect, useMemo } from 'react';
import { Modal, Button, Spin } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import loadable from '@loadable/component';
import $ from 'cash-dom';
import dayjs from 'dayjs';

import { GET_FILE_STREAM } from '@/config/url';
import { insertScript } from '@/utils';

import styles from './index.module.scss';

export default props => {
    const initState = () => ({
        loading: true,
        imageUrl: '',
    });
    const [state, setState] = useState(initState);
    const { open, dataSource={}, onCancel, onOk } = props;
    const { userInfo={} } = useSelector(s => s.common);

    const waitImages = () => {
        const posterElement = document.getElementById('poster-image');
        if (!posterElement) return Promise.resolve();
        const imgs = Array.from(posterElement.querySelectorAll('img'));
        return Promise.all(
            imgs.map(img => img && (img.complete ? Promise.resolve() : new Promise(r => { img.onload = r; img.onerror = r; })))
        );
    };

    const downloadPoster = () => {
        const posterElement = document.getElementById('poster-image');
        if (!posterElement) {
            alert('海报元素未找到');
            setState(o => ({ ...o, imageUrl: '', loading: false }));
            return;
        }

        // 检查 html2canvas 是否已加载
        if (typeof html2canvas === 'undefined') {
            alert('html2canvas 库未加载，请稍后再试');
            setState(o => ({ ...o, imageUrl: '', loading: false }));
            return;
        }

        // 使用 html2canvas 将 DOM 元素转换为 canvas
        html2canvas(posterElement, {
            useCORS: true,
            allowTaint: true,
            scale: 2, // 提高图片质量
            backgroundColor: null,
            logging: false,
            width: posterElement.offsetWidth,
            height: posterElement.offsetHeight
        }).then(canvas => {
            // 将 canvas 转换为 blob 并下载
            canvas.toBlob((blob) => {
                if (!blob) {
                    alert('生成图片失败');
                    return;
                }

                const url = URL.createObjectURL(blob);
                // URL.revokeObjectURL(url);
                setState(o => ({ ...o, imageUrl: url, loading: false }));
            }, 'image/png', 1.0);
        }).catch(error => {
            console.error('生成海报失败:', error);
            alert('生成海报失败，请重试');
            setState(o => ({ ...o, imageUrl: '', loading: false }));
        });
    }

    const initQrCode = (url) => {
        $('#qrcode').empty();
        new QRCode(document.getElementById("qrcode"), {
            text: url,
            width: 100,
            height: 100,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        });
    };
    
    const afterOpenChange = async open => {
        if(open) {
            initQrCode(location.href);
            await waitImages();
            downloadPoster();
        }
    }

    useEffect(() => {
        const { imageUrl } = state;

        insertScript('/js/qrcode.min.js');
        insertScript('/js/html2canvas.min.js');

        return () => {
            imageUrl && URL.revokeObjectURL(imageUrl);
        }
    }, []);
    
    const postInfo = useMemo(() => {
        // 优先使用直接字段，如果不存在则从数组中提取第一个
        let name = '';
        if (dataSource?.goodsName) {
            name = dataSource.goodsName;
        } else if (dataSource?.charactarList && Array.isArray(dataSource.charactarList) && dataSource.charactarList.length > 0) {
            name = dataSource.charactarList[0]?.charactarName || '';
        } else if (dataSource?.seriesList && Array.isArray(dataSource.seriesList) && dataSource.seriesList.length > 0) {
            name = dataSource.seriesList[0]?.seriesName || '';
        }
        const image = dataSource?.mainGoodsImages || dataSource?.mainCharactarImage || dataSource?.mainSeriesImage || '';

        return {name, image};
    }, [dataSource]);

    return (
        <Modal
            header={null}
            footer={null}
            maskClosable={true}
            closable={false}
            onCancel={onCancel}
            open={open}
            rootClassName={styles['modal-root']}
            width={360}
            afterOpenChange={afterOpenChange}
            destroyOnHidden={true}
        >
            <div className={styles['container']} id="poster-image">
                { !state.loading && state.imageUrl && <img className={styles['poster-image']} src={state.imageUrl} alt="海报" /> }
                <div className={styles['line']}></div>
                <div className={styles['title']}>{postInfo.name || '--'}</div>
                { dataSource?.introduce ? <div className={styles['desc']}>{dataSource?.introduce || '--'}</div> : null}
                <div className={styles['image']}><img src={postInfo.image ? `${GET_FILE_STREAM}?url=${postInfo.image}` : '/images/poster.png'} alt="" /></div>
                
                <div className={styles['footer']}>
                    <div className={styles['left']}>
                        <div className={styles['logo']}>
                            <img src="/images/logo.png" alt="" />
                            {/* <div className={styles['web-name']}>{WEB_NAME}</div> */}
                        </div>
                        <div className={styles['text']}>扫描二维码查看详情</div>
                    </div>
                    <div className={styles['right']}><div id="qrcode"></div></div>
                </div>
            </div>

            <div className={styles['action']}>{state.loading ? '海报生成中...' : '长按图片/右键下载海报'}</div>
        </Modal>
    );
}
